<template>
  <div class="route-page box">
    <section class="content beauty-scroller-bar">
      <a-card
        class="content-card"
        :bordered="false"
        :bodyStyle="{
          padding: '10px',
          width: '100%',
          display: 'flex',
        }"
      >
        <div class="left">
          <section
            style="
              height: 32px;
              padding: 0 10px 0 5px;
              display: flex;
              justify-content: space-between;
              align-items: center;
            "
          >
            <div style="color: #333; font-weight: 600; font-size: 16px">
              分类管理
            </div>
            <a-button type="text" @click="editCate">
              <template #icon
                ><PlusOutlined style="color: #666; font-size: 18px"
              /></template>
            </a-button>
          </section>
          <section class="cate-list-wrap">
            <div class="cate-list hide-scroller-bar">
              <li
                class="cate-list-item"
                @click="onCateClick(cateAll)"
                :class="
                  currentCate.id == cateAll.id ? 'cate-list-item-current' : ''
                "
                v-if="showCheckAll"
              >
                <span>{{ cateAll.name }}</span>
              </li>
              <template v-if="cateList.length > 0">
                <draggable
                  group="dragList"
                  v-model="cateList"
                  v-bind="dragOptions"
                  item-key="id"
                  @end="onDragFinish"
                >
                  <template #item="{ element }">
                    <li
                      class="cate-list-item"
                      @click="onCateClick(element)"
                      :class="
                        currentCate.id == element.id
                          ? 'cate-list-item-current'
                          : ''
                      "
                    >
                      <span>{{ element.cat_name }}</span>
                      <a-dropdown :trigger="['click']" v-if="!element.is_root">
                        <span
                          class="ant-dropdown-link"
                          @click.stop
                          style="padding: 0 5px"
                        >
                          <MoreOutlined />
                        </span>
                        <template #overlay>
                          <a-menu>
                            <a-menu-item key="0">
                              <a-button
                                type="link"
                                style="
                                  width: 100%;
                                  text-align: center;
                                  padding: 0 16px;
                                  margin: 0;
                                "
                                @click="editCate(element.id)"
                                >编辑分类</a-button
                              >
                            </a-menu-item>
                            <a-menu-item key="1">
                              <a-button
                                type="link"
                                danger
                                style="
                                  width: 100%;
                                  text-align: center;
                                  padding: 0 16px;
                                  margin: 0;
                                "
                                @click="deleteCate(element.id)"
                                >删除分类</a-button
                              >
                            </a-menu-item>
                          </a-menu>
                        </template>
                      </a-dropdown>
                    </li>
                  </template>
                </draggable>
              </template>
            </div>
          </section>
        </div>
        <div class="right">
          <a-row align="middle" justify="space-between">
            <a-col>
              <a-input-search
                v-model:value="keywords"
                placeholder="请输入审批名称"
                enter-button
                @search="getList"
                allowClear
              />
            </a-col>
            <a-col>
              <a-button type="primary" @click="editClick()">
                <PlusOutlined />新建审批
              </a-button>
            </a-col>
          </a-row>
          <draggable
            group="dragList"
            v-model="dataSource"
            v-bind="dragOptions"
            handle=".order-icon"
            item-key="id"
            @end="onApprovalDragFinish"
            class="approval-list-wrap beauty-scroller-bar"
          >
            <template #item="{ element: approval }">
              <div class="approval-list">
                <a-avatar :src="approval.icon" :size="48" />
                <div class="approval-name">
                  <div class="text-black">
                    <span>{{ approval.name }}</span>
                    <a-tag v-if="approval.from_third" style="margin-left: 10px">
                      由{{ approval.from_third }}提供
                    </a-tag>
                  </div>
                  <div class="text-gray">{{ approval.desc }}</div>
                </div>
                <div class="user-type">
                  <span v-if="approval.from_third">
                    可在{{ approval.from_third }}应用中发起
                  </span>
                  <span v-else>
                    {{ getUserType(approval.start_user_type) }}
                  </span>
                </div>
                <a-space>
                  <a-tooltip>
                    <template #title>编辑审批</template>
                    <a-button type="link" @click="editClick(approval.id)">
                      <template #icon>
                        <FormOutlined />
                      </template>
                    </a-button>
                  </a-tooltip>
                  <a-tooltip v-if="approval.status == 4">
                    <template #title> 启用审批 </template>
                    <a-button
                      type="link"
                      @click="changeApprovalStatus(approval)"
                    >
                      <template #icon>
                        <CheckCircleOutlined />
                      </template>
                    </a-button>
                  </a-tooltip>
                  <a-tooltip v-if="approval.status == 1">
                    <template #title> 禁用审批 </template>
                    <a-button
                      type="link"
                      danger
                      @click="changeApprovalStatus(approval)"
                      :disabled="!!approval.alias"
                    >
                      <template #icon>
                        <StopOutlined />
                      </template>
                    </a-button>
                  </a-tooltip>
                  <a-tooltip>
                    <template #title>删除审批</template>
                    <a-button
                      type="link"
                      danger
                      @click="removeApproval(approval.id)"
                      :disabled="!!approval.alias"
                    >
                      <template #icon>
                        <DeleteOutlined />
                      </template>
                    </a-button>
                  </a-tooltip>
                  <a-tooltip>
                    <template #title>拖拽排序</template>
                    <div class="order-icon">
                      <MenuOutlined />
                    </div>
                  </a-tooltip>
                </a-space>
              </div>
            </template>
          </draggable>
        </div>
      </a-card>
    </section>

    <!-- 新增、编辑分类 -->
    <EditCategory
      :visible="editCateVisible"
      :id="editCateId"
      @onClose="editCateVisible = false"
      @success="onEditCateSuccess"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  onBeforeUnmount,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
  computed,
  createVNode,
  nextTick,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  MoreOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  FormOutlined,
  DeleteOutlined,
  MenuOutlined,
  StopOutlined,
  CheckCircleOutlined,
} from "@ant-design/icons-vue";
import { Form, message, Modal } from "ant-design-vue";
import store from "../../../store";
import request from "../../../common/utils/request";
import draggable from "vuedraggable";
import EditCategory from "./module/EditCategory.vue";
import common from "../SetApproval/js/common";

export default defineComponent({
  name: "FeeTypeSetting",
  components: {
    MoreOutlined,
    draggable,
    PlusOutlined,
    EditCategory,
    FormOutlined,
    DeleteOutlined,
    MenuOutlined,
    StopOutlined,
    CheckCircleOutlined,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const state = reactive({
      cateKeywords: "",
      cateList: [], //费用分类列表
      currentCate: {
        name: "所有",
        id: 0,
      },
      cateAll: {
        name: "所有",
        id: 0,
      },
      showCheckAll: true,
      editCateVisible: false,
      editCateId: null,

      keywords: "",
      dataSource: [], //费用类型列表
      total: 0,
      page: 1,
      pageSize: 20,
      columns: [
        {
          title: "费用名称",
          dataIndex: "name",
          width: "20%",
          align: "center",
        },
        {
          title: "所属分类",
          dataIndex: "category_name",
          width: "20%",
          align: "center",
        },
        {
          title: "排序",
          dataIndex: "sort",
          width: "20%",
          align: "center",
        },
        {
          title: "状态",
          width: "20%",
          slots: {
            customRender: "status",
          },
          align: "center",
        },
        {
          title: "操作",
          slots: {
            customRender: "action",
          },
          width: "20%",
          align: "center",
        },
      ],
      editVisible: false,
      editId: null,
    });

    const getCateList = () => {
      let params = {};

      request
        .get("/work_approval", "/tenant/category/list", { ...params })
        .then((res) => {
          if (res.result) {
            state.cateList = res.result;
            state.currentCate = state.cateAll;

            state.page = 1;
            state.pageSize = 20;
            getList();
          }
        });
    };

    const onCateClick = (item) => {
      if (state.currentCate.id == item.id) {
        return;
      }
      state.currentCate = item;
      getList();
    };

    const editCate = (id) => {
      state.editCateId = 0;
      if (id && id > 0) {
        state.editCateId = id;
      }
      state.editCateVisible = true;
    };

    const deleteCate = (id) => {
      Modal.confirm({
        title: () => `确定要删除吗？`,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          request
            .del("/work_approval", "/tenant/category/delete", {
              id,
            })
            .then((res) => {
              message.success("删除成功");
              getCateList();
            });
        },
      });
    };

    const onEditCateSuccess = () => {
      message.success("保存成功");
      state.editCateVisible = false;
      getCateList();
    };

    const init = () => {
      getCateList();
    };

    init();

    const dragOptions = computed(() => {
      return {
        animation: 200,
        group: "description",
        disabled: false,
        ghostClass: "ghost",
      };
    });

    let dragTimer1 = null;
    const onDragFinish = (e) => {
      if (dragTimer1) {
        clearTimeout(dragTimer1);
        dragTimer1 = null;
      }
      dragTimer1 = setTimeout(() => {
        let result = state.cateList.map((item, index) => ({
          id: item.id,
          cat_sort: state.cateList.length - index,
        }));
        request
          .post("/work_approval", "/tenant/category/sort", { data: result })
          .then((res) => {});
      }, 500);
    };

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
    }));

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      getList();
    };

    const getList = () => {
      let params = {
        page: state.page,
        limit: state.pageSize,
      };

      if (state.currentCate && state.currentCate.id) {
        params.cat_id = state.currentCate.id;
      }

      if (state.keywords) {
        params.name = state.keywords;
      }

      request
        .get("/work_approval", "/tenant/approval/list", { ...params })
        .then((res) => {
          if (res.result) {
            state.dataSource = res.result;
          }
          state.total = res.total;
        });
    };

    const editClick = (id) => {
      let title = '新建审批'
      let url = '/tenantApproval/set?'
      if (id) {
        title = '编辑审批'
        url= `/tenantApproval/set?id=${id}`
      }
      let temId = id?id:0
      if (window.__MICRO_APP_ENVIRONMENT__) {
        const lastMicroId = window.microApp?.appName
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `org_workApproval_setTenantApproval_${temId}`,
            app: 'workApproval',
            name: title,
            url: `${url}&microId=${lastMicroId}`,
          }
        })
      }
  };

    const onEditSuccess = () => {
      state.editVisible = false;
      getList();
    };

    // 审批-谁可以发起这个审批
    const getUserType = (userType) => {
      const type = common.memberOptions.find((item) => item.value == userType);
      return type.label;
    };

    // 修改审批状态
    const changeApprovalStatus = (approval) => {
      request
        .post("/work_approval", "/tenant/approval/status", {
          id: approval.id,
          status: approval.status == 1 ? 4 : 1,
          needMsg: true,
        })
        .then((res) => {
          message.success("操作成功");
          getList();
        });
    };

    // 删除审批
    const removeApproval = (id) => {
      Modal.confirm({
        title: () => `确定要删除吗？`,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          request
            .del("/work_approval", "/tenant/approval/delete", {
              id,
            })
            .then((res) => {
              message.success("删除成功");
              getList();
            });
        },
      });
    };

    let dragTimer2 = null;
    const onApprovalDragFinish = (e) => {
      if (dragTimer2) {
        clearTimeout(dragTimer2);
        dragTimer2 = null;
      }
      dragTimer2 = setTimeout(() => {
        let result = state.dataSource.map((item, index) => ({
          id: item.id,
          sort: state.dataSource.length - index,
        }));
        request
          .post("/work_approval", "/tenant/approval/sort", { data: result })
          .then((res) => {});
      }, 500);
    };

    return {
      ...toRefs(state),
      onCateClick,
      getCateList,
      dragOptions,
      onDragFinish,
      editCate,
      deleteCate,
      onEditCateSuccess,

      pagination,
      handleTableChange,
      getList,
      editClick,
      onEditSuccess,
      getUserType,
      changeApprovalStatus,
      removeApproval,
      onApprovalDragFinish,
    };
  },
});
</script>

<style lang="less" scoped>
.route-page {
  width: 100%;
  height: 100%;

  .content {
    flex: 1;
    padding: 0 10px;
    height: 100%;

    .content-card {
      width: 100%;
      height: 100%;
      display: flex;

      .left {
        width: 220px;
        height: 100%;
        border-right: 1px solid #f1f1f1;

        .cate-list-wrap {
          height: calc(100% - 32px);
          position: relative;
          padding-top: 10px;

          .cate-list {
            height: 100%;
            overflow: hidden auto;
            padding: 0 10px 70px 0;

            .cate-list-item {
              padding: 8px 0 8px 10px;
              margin-top: 5px;
              border-radius: 4px;
              cursor: pointer;
              display: flex;
              justify-content: space-between;
              align-items: center;
            }

            .cate-list-item-current {
              background-color: #cceaff;
            }
          }
        }
      }

      .right {
        width: calc(100% - 220px);
        padding: 0 10px;

        .approval-list-wrap {
          width: 100%;
          height: calc(100% - 62px);
          overflow: hidden auto;
          margin-top: 20px;
          padding: 0 10px;

          .approval-list {
            display: flex;
            align-items: center;
            padding: 15px 10px;
            user-select: none;
            border-bottom: 1px solid #eee;
            .approval-name {
              flex: 1;
              margin: 0 20px;
              line-height: 24px;
              font-weight: 500;
            }
            .user-type {
              flex: 1;
            }
            .order-icon {
              cursor: all-scroll;
              margin-left: 10px;
              padding-right: 15px;
            }
          }
        }
      }
    }
  }
}
</style>
